<template>
	<view class="contract-edit">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true" backIcon="cuIcon-close">
			<block slot="backText">关闭</block>
			<block slot="content">合同网签</block>
		</cu-custom>
		<view v-if="!showProgress">
			<!-- ====================== 合同基本信息 ========================  -->
			<form>
				<!-- ====================== 合同信息 ========================  -->
				<view>
					<view class="cu-bar text-gray">
						<view class="action">
							 合同信息
						</view>
					</view>
					<view class="cu-form-group">
						<view class="title"><text class="icon-ruzhuyixiang-yixiangbianhao"></text> 合同编号:</view>
						<!-- <input  name="input" v-model="contract.ContractCode" placeholder="请输入合同编号"></input> -->
						<text>{{contract.ContractCode}}</text>
					</view>
					<view class="cu-form-group">
						<view class="title"><text class="icon-jine1"></text>交易金额(元):</view>
						<!-- <input placeholder="请输入交易金额,单位(元)" name="input" v-model="contract.Amount"></input> -->
						<text>{{contract.Amount}}</text>
					</view>
			
					<view class="cu-form-group">
						<view class="title"><text class="icon-riqi"></text>移交日期</view>
						<text>{{contract.HandoverDate}}</text>
						</picker>
					</view>
				</view>
				
				<!-- ====================== 房屋信息 ========================  -->
				<view class="house">
					<view class="cu-bar text-gray">
						<view class="action">房屋信息</view>
					</view>
					<view class="cu-form-group">
						<view class="title"><text class="icon-0301renxiang"></text>房屋权利人</view>
						<text> {{house.Name}} </text>
					</view>	
					<view class="cu-form-group">
						<view class="title"><text class="icon-2shenfenzhenghaoma"></text>权利人身份证号</view>
						<text>{{house.IdentityNo}}</text>
					</view>	
					<view class="cu-form-group">
						<view class="title"><text class="icon-zhishichanquan"></text>产权号</view>
						<text>{{house.CertificateNo}}</text>
					</view>	
					<view class="cu-form-group address">
						<view class="title"><text class="cuIcon-location"></text>地址</view>
						<text>{{house.Address}}</text>
					</view>
					<!-- <view class="cu-form-group">
						<view class="title">建筑面积</view>
						<text>{{house.ConstructionArea}}平方米</text>
					</view>
					<view class="cu-form-group">
						<view class="title">室内建筑面积</view>
						<text>{{house.ComprisingArea}}平方米</text>
					</view>	 -->			
				</view>
			</form>
			
			<!-- ====================== 当事人 ========================  -->			
			<view>
				<view>
					<view class="cu-bar bg-white  margin-top">
						<view class="action"><text class="cuIcon-title text-blue"></text>卖方人员</view>
					</view>
					
					<view class="cu-bar   padding-left-xs padding-right-xs text-gray" style="flex-wrap:wrap;">
						<block v-for="(item, index) in PeopleList" :key="index">
							<view class=" margin-xs padding-sm flex bg-white solid radius" v-if="item.Role == 2">
								<view class="cuIcon-friendfill text-blue"></view>
								<view class="padding-left-xs padding-right-xs">{{ item.Name }}:</view>
								<view>{{ _Property[item.Property] }}</view>
							</view>						
						</block>
					</view>
				</view>				
				<view>
					<view class="cu-bar bg-white   margin-top">
						<view class="action ">
							<text class="cuIcon-title text-blue"></text>买方人员
						</view>
					</view>
					<view class="cu-bar   padding-left-xs padding-right-xs text-gray" style="flex-wrap:wrap;">
						<block v-for="(item, index) in PeopleList" :key="index">
							<view class=" margin-xs padding-sm flex bg-white solid radius" v-if="item.Role == 1">
								<view class="cuIcon-friendfill text-blue"></view>
								<view class="padding-left-xs padding-right-xs">{{ item.Name }}:</view>
								<view>{{ _Property[item.Property] }}</view>
							</view>						
						</block>
					</view>				
				</view>
			</view>
			<!-- ===================================== 附件信息 ============================ -->
			<view>				
				<view class="margin-top cu-form-group">
					<view class="title">合同word文档</view>					
					<view   v-if="downloading" class=" line-blue" >下载中</view>					
					<button v-else class="cu-btn cu-tag line-blue round"  @click="downloadFile()" :data-target="2">
						<text class="cuIcon-down"></text>重新下载</button>
				</view>
				<view class="cu-form-group " v-if="!downloading" style="border: none;">
					<textarea  v-model="dir" placeholder="" :auto-height="true"/>
					<view  class="round cu-tag line-blue margin-left" @click="openDocument()"><text class="cuIcon-forward"></text> 打开文件</view>
				</view>
				<view class="cu-form-group" v-if="downloading"  style="border: none;">
					<view class="cu-progress striped round  active">
						<view class="bg-blue" :style="[{ width: downloadBarWidth + '%' }]"></view>
					</view>
					<text class="margin-left">{{ downloadBarWidth + '%' }}</text>
				</view>
				
				<view class="cu-bar bg-white margin-top">
					<view class="action">合同签字页</view>
					<view class="action">{{signImageList.length}}/{{signImageMax}}</view>
				</view>
				<view class="cu-form-group">
					<view class="grid col-4 grid-square flex-sub">
						<view class="bg-img" v-for="(item,index) in signImageList" :key="index" @tap="ViewImage($event, 'signImageList')" :data-url="signImageList[index]">
						 <image :src="signImageList[index]" mode="aspectFill"></image>
							<view class="cu-tag bg-red" @tap.stop="DelImg($event, 'signImageList')" :data-index="index">
								<text class='cuIcon-close'></text>
							</view>
						</view>
						<view class="solids" @tap="ChooseImage('signImageList', signImageMax - signImageList.length)" v-if="signImageList.length<4">
							<text class='cuIcon-cameraadd'></text>
						</view>
					</view>
				</view>
				
				<view class="cu-bar bg-white margin-top">
					<view class="action">
						合同信息及其他要件
					</view>
					<view class="action">
						{{otherImgList.length}}/{{otherImgMax}}
					</view>
				</view>
				<view class="cu-form-group">
					<view class="grid col-4 grid-square flex-sub">
						<view class="bg-img" v-for="(item,index) in otherImgList" :key="index" @tap="ViewImage($event, 'otherImgList')" :data-url="otherImgList[index]">
						 <image :src="otherImgList[index]" mode="aspectFill"></image>
							<view class="cu-tag bg-red" @tap.stop="DelImg($event, 'otherImgList')" :data-index="index">
								<text class='cuIcon-close'></text>
							</view>
						</view>
						<view class="solids" @tap="ChooseImage('otherImgList', otherImgMax - otherImgList.length)" v-if="otherImgList.length<4">
							<text class='cuIcon-cameraadd'></text>
						</view>
					</view>
				</view>		
			</view>		
			
		</view>
		
		
		
		<view class="padding" v-if="!showProgress">
			<button class="cu-btn block bg-blue margin-tb-sm lg" :class="isCanSubmite ? '' : 'btn-disabled' " @click="submitSign">
				提交网签</button>
		</view>
		<load-progress :showProgress="showProgress"></load-progress>
	</view>
</template>

<script>
	let _this = null;
	import { getContractInfo, editContract } from '@/common/api/zft-contract.js'
	import { fileHost as _downloadDocHost } from '@/common/config/index.js'
	import { Property, Role, Group } from '@/common/config/zft.js'
	import { urlTobase64 } from '@/common/utils/common.js'
	import { setContractDir, getContractDir } from '@/common/localStorage/contract.js'
	export default {
		data() {			
			return {
				dir: '',
				contract: {
					num: '566446',
					money: '356642',
					date: '2016-9-6'
				},
				location: '',
				// 签字页
				signImageList: [],
				signImageMax: 2,
				otherImgMax: 4,
				otherImgList: [],
				showProgress: false,
				house: {},
				// 
				SignId: '',
				downloading: false,
				downloadBarWidth: 0,
				PeopleList: [],
				isloading: false,
				PeopleConfig: {
				    Userid: '',
				    Address: '',
				    Phone: '',
					// Name: '',
				    Remarks: '',
				    Role: 1,
				    Property: 1,
				    IsAgent: false,
				},
			}
		},
		onLoad(route) {	
			_this = this
			// this.downloadFile()
			if (route.SignId) {
				this.SignId = route.SignId
				this.getContractInfo()
				this.dir = getContractDir(this.SignId)
			} else {
				this.showToast('当前页面存在错误，请关闭当前页面重试！')
			}	
		},
		
		computed: {
			isCanSubmite() {
				return this.signImageList.length > 0 && this.otherImgList.length > 0
			},
			_Property() {
				return Property
			},
			_Role() {
				return Role
			}
		},
		methods: {
			
			// 获取合同列表
			getContractInfo() {
				this.showProgress = true
				let s = {
					// SignId: ''	网签表id	string		是,
					SignId: this.SignId
				}
				getContractInfo(s).then(({data}) => {
					console.log('获取到的合同信息', data)
					if (data.msgcode == 1000) {
						this.contract = data.data
						this.contract.Amount = data.data.CS_SignZFT.Amount
						this.contract.HandoverDate = data.data.CS_SignZFT.HandoverDate
						this.PeopleList = data.data.CS_SignPeople
						let img = data.data.CS_SignAppendices
						this.signImageList = []
						this.otherImgList = []
						for (let i = 0; i < img.length; i++) {
							if (img[i].Group == 1) {
								this.signImageList.push(this.fileHost + img[i].Url)
							} else if (img[i].Group == 2) {
								this.otherImgList.push(this.fileHost + img[i].Url)
							}
						}
						// this.PeopleList = []
						// for (let i = 0; i < data.data.CS_SignPeople.length; i++) {
						// 	// let obj = Object.assign({}, this.PeopleConfig,  data.data.CS_SignPeople[i])
						// 	this.PeopleList[i] = {}
						// 	for (let prop in this.PeopleConfig) {
						// 		this.PeopleList[i][prop] = data.data.CS_SignPeople[i][prop]
						// 	}
						// 	// this.PeopleList.push(obj)
						// }
						this.house = data.data.CS_SignHouse[0]
						console.log('this.PeopleList', this.PeopleList)
						
					} else {
						this.showToast(data.msg)
					}
				}).then(() => {
					this.showProgress = false
				})
			},
			
			// 选择图片
			ChooseImage(str, count) {
				uni.chooseImage({
					// count: 4, //默认9
					count,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
					success: (res) => {
						// if (_this.signImageList.length != 0) {
						// 	_this.signImageList = _this.signImageList.concat(res.tempFilePaths)
						// } else {
						// 	_this.signImageList = res.tempFilePaths
						// }
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							urlTobase64(res.tempFilePaths[i]).then(data => {
							console.log('base  64 data.data', data.data)
								_this[str].push(data.data)
								
							}).catch(err => {
								this.showToast('图片转换出错，请重试', err)
							})	
						}											
					}
				});
			},
			
			// 图片预览
			ViewImage(e, str) {
				uni.previewImage({
					urls: _this[str],
					current: e.currentTarget.dataset.url
				});
			},
			
			// 删除图片
			DelImg(e, str) {
				// uni.showModal({
				// 	title: '提示',
				// 	content: '确定要删除？',
				// 	cancelText: '再看看',
				// 	confirmText: '再见',
				// 	success: res => {
				// 		if (res.confirm) {
				// 			_this[str].splice(e.currentTarget.dataset.index, 1)
				// 		}
				// 	}
				// })
				_this[str].splice(e.currentTarget.dataset.index, 1)
			},
			
			// 下载文件
			downloadFile () {
				// const url = 'http://ricostacruz.com/nprogress/'
				if (this.downloading) return
				// const url = _downloadDocHost
				this.downloading = true
				const url = _downloadDocHost + 'Files/HousingZFT/SignContracts/CL_2019072100002_aa176.doc'
				this.downloadBarWidth = 0
				const task =  uni.downloadFile({
					url,
					complete: res => {
						console.log('下载文件 res: ', res)
						if (res.statusCode == 200) {
							this.saveFile(res.tempFilePath)
						} else {
							this.showToast('下载失败！')
						}
						setTimeout(() => {
							this.downloading = false
						}, 800);
					}
				})
				task.onProgressUpdate(res => {
					console.log('下载 res', res)
					console.log('res.progress 下载进度百分比 % ：', res.progress)	
					this.downloadBarWidth = res.progress
					// console.log('res.已经下载的数据长度', res.totalBytesExpectedToWrite)
					// console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
				})
			},
			
			// 保存文件
			saveFile(tempFilePath) {
				uni.saveFile({
					tempFilePath,
					success: res => {
						console.log('保存文件成功 res: ', res)
						setContractDir(this.SignId, res.savedFilePath)
						_this.dir = res.savedFilePath
						_this.getSavedFileList()
					}
				})
			},
			
			// 打开文件
			openDocument() {
				let filePath = getContractDir(this.SignId)
				uni.openDocument({
					filePath,
					// fileType: 'doc',
					success: res => {
						console.log('打开文件成功：', res)
					},
					fail: res => {
						this.showToast('打开文件失败')
						console.log('打开文件失败：', res)
					}
				})
			},
			
			// 获取本地已保存的文件列表。
			getSavedFileList() {
				uni.getSavedFileList({
					complete: res => {
						console.log('获取本地保存的文件列表 res: ', res)
						if (res.statusCode === 200) {

						}
					}
				})
			},
			
			
			
			// 转换images信息
			toImageInfo(arr, Group) {
				let s = []
				for (let i = 0; i < arr.length; i++) {
					s.push({
						Title: '标题',
						ImgCode: arr[i],
						Url: '',
						Group: Group,
						Descript: '说明',
						Remarks: '备注'
					})
				}
				return s
			},
			
			// 提交网签
			submitSign () {
				if (this.isloading)return
				/**
				 0：其它
				 9：合同word
				 1：签字页
				 2：合同信息页
				*/
				let signImgs = this.toImageInfo(this.otherImgList, 1)
				let otherImgs = this.toImageInfo(this.signImageList, 2)
				let Appendices = signImgs.concat(otherImgs)
				if (signImgs.length < 1) { 
					this.showToast(`请上传合同签字照片`)
					return
				}
				if (otherImgs.length < 1) {
					this.showToast(`合同信息及其他要件`)
					return
				}
					
				let json = {
					// SignId 网签表id
					SignId: this.SignId,
					// RoomId:	RoomId
					// RoomId:	this.contract.SignRoomId,	
					// ContractCode	合同编号
					// ContractCode: this.contract.ContractCode,
					// Amount	合同金额
					Amount: Number(this.contract.Amount),
					// HandoverDate	交房日期,  DateTime
					HandoverDate: this.contract.HandoverDate,
					// SignDate	网签日期
					SignDate: '',
					// AddUserid	添加人Userid
					EditUserid: this.$store.state.user.userList[0].Userid,
					// AddUserid: this.$store.state.user.userList[0].Userid,
					/*------------------*/
					People: this.PeopleList,
					// People	合同当事人  []
						// Userid	Userid
						// Address	地址
						// Phone	电话
						// Remarks	备注
						// Role	角色
						// Property	性质
						// IsAgent	是否代理人
					/*------------------*/
					/*------------------ */
					Appendices,
					// Appendices	合同附件（图片） []
						// Title	标题
						// Title: this.contract.title,
						// ImgCode	图片转Base64字符串
						// Url	URL
						// Group	分组 0：其它 9：合同word  1：签字页  2：合同信息页
						// Descript	说明
						// Remarks	备注	
					/*------------------ */				
				}
				
				
				this.loading = true
				// let body = { json: JSON.stringify(json) }
				console.log('合同网签， 提交的信息 ： ', json)
				/////////////////////////////
				// return true;
				/////////////////////////////////////
				editContract(json).then(({data}) => {	
					console.log('合同网签返回的信息:', data)	
					if(data.msgcode == 1000) {
						this.showToast('提交成功')
						
					} else {
						this.showToast(data.msg)
					}
					this.loading = false
				}).catch(() => {
					this.loading = false
					this.showToast('生成合同失败，请稍后重试')
				})
			},
			
		
		}
	}
</script>

<style lang="scss" scoped>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
	.cu-form-group .title {
		[class*="icon-"],
		[class*="cuIcon-"] {
			margin-right: 15upx;
		}
	}

</style>
